package com.padgett.resourcemanagement;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.appengine.auth.oauth2.AbstractAppEngineAuthorizationCodeServlet;
import com.google.api.client.extensions.appengine.auth.oauth2.AppEngineCredentialStore;
import com.google.api.client.extensions.appengine.http.UrlFetchTransport;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.Drive.About;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.ChildList;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * Retrieve a list of overdue services. If current User is not admin, it will
 * retrieve all owning services, if it is admin, it will retrieve all overdue
 * ones including Accountant names.
 * 
 * @author andyleung
 * 
 */
@SuppressWarnings("serial")
public class GetOverdueServicesServlet extends AbstractAppEngineAuthorizationCodeServlet{
	public static final String clientId = "1056776873291-g70otb3kmf1evnb2a4d050brcap4trck.apps.googleusercontent.com";
	public static final String secret = "7C6_iUJ7X4UN-gUJyOFbYPxF";
	private AppEngineCredentialStore credentialStore=new AppEngineCredentialStore();
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		UserService userService=UserServiceFactory.getUserService();
		String thisURL = req.getRequestURI();
		if(req.getUserPrincipal()!=null&&userService.getCurrentUser()!=null){
			String userId=userService.getCurrentUser().getUserId();
			//resp.getWriter().write("User ID:"+userId);
			//String userId="andy.leung@castbefore.com";
			Credential credential=initializeFlow().loadCredential(userId);
			/*boolean loaded=credentialStore.load(userId, credential);
			if(loaded){
				resp.getWriter().write("Loaded:"+credential.getRefreshToken());
			}else{
				resp.getWriter().write("No loaded<br/>");
			}*/
			if(credential==null){
				resp.getWriter().write("<br/>Null credential:"+credential);
			}else{
				Drive drive=new Drive.Builder(new NetHttpTransport(), new JacksonFactory(), credential).build();
				Files files=drive.files();
				FileList list=files.list().execute();
				About about=drive.about();
				com.google.api.services.drive.model.About loadedAbout=about.get().execute();
				String rootFolderId=loadedAbout.getRootFolderId();
				/*
				com.google.api.services.drive.model.File newFile=new com.google.api.services.drive.model.File();
				newFile.setDescription("Testing Description");
				newFile.setEditable(true);
				newFile.setTitle("Testing title");
				newFile.setWritersCanShare(true);
				com.google.api.services.drive.model.File insertedFile=drive.files().insert(newFile).execute();
				resp.getWriter().write("insertedFile("+insertedFile.getId()+") Size:"+insertedFile.getFileSize()+", <br/>");
				*/
				
				ChildList childs=drive.children().list(rootFolderId).execute();
				List<com.google.api.services.drive.model.ChildReference> loadedChildList=childs.getItems();
				resp.getWriter().write("loadedChildList("+loadedAbout.getName()+") Size:"+loadedChildList.size()+", <br/>");
				List<File> allFiles=list.getItems();
				resp.getWriter().write("allFiles Size:"+allFiles.size());
				for(File file:allFiles){
					resp.getWriter().write("filename:"+file.getId()+", title:"+file.getTitle()+"<br/>");
				}
			}
			/*
			Calendar calendar=new Calendar.Builder(new NetHttpTransport(),new JacksonFactory(),credential).build();
			CalendarList calendarList=calendar.calendarList();
			com.google.api.services.calendar.model.CalendarList list=calendarList.list().execute();
			java.util.List<CalendarListEntry> entries=list.getItems();
			for(CalendarListEntry entry:entries){
				resp.getWriter().write("Summary:"+entry.getSummary()+", ID:"+entry.getId()+"<br/>");
			}*/
		}else{
			resp.getWriter().println("<p>Please <a href=\"" +
                    userService.createLoginURL(thisURL) +
                    "\">sign in</a>.</p>");
		}
	}

	@Override
	protected String getRedirectUri(HttpServletRequest req)
			throws ServletException, IOException {
		GenericUrl url = new GenericUrl(req.getRequestURL().toString());
		url.setRawPath("/oauth2callback");
		return url.build();
	}

	@Override
	protected AuthorizationCodeFlow initializeFlow() throws IOException {
		AuthorizationCodeFlow flow=
		 new GoogleAuthorizationCodeFlow.Builder(new UrlFetchTransport(),
				new JacksonFactory(), clientId,
				secret,
				Arrays.asList(DriveScopes.DRIVE,"https://spreadsheets.google.com/feeds","https://docs.google.com/feeds"))
				.setCredentialStore(credentialStore).setAccessType("online").build();
		return flow;
	}
}
